# coding=utf-8
# 获取指数涨跌
import os
import re
import sys

import akshare as ak
import pandas
import pandas as pd
from loguru import logger

from models.stock_model import StockNumber, DayInfo
from mylib.download_all import analysis_stock
from mylib.mycsv import sort_csv


def run(d=1, n=3):
    if d:
        sz_index_df = ak.index_zh_a_hist(symbol="000001", period="daily")
        df_sorted = sz_index_df.sort_values(by='日期', ascending=False)
        df_sorted.to_csv("shanghai_index.csv", index=False)
    else:
        df_sorted = pd.read_csv('shanghai_index.csv')
    n_arr = []
    for item in df_sorted['涨跌幅']:
        if n_arr.count('1') > n:
            break
        x = '0' if item > 0 else '1'
        n_arr.append(x)
    arr_a = ['0b1']
    arr_a.extend(n_arr)
    bin_arr_a = ''.join(arr_a)
    to_date = eval(str(list(df_sorted['日期'])[0]).replace('-', ''))
    return bin_arr_a, len(arr_a), to_date


def get_a_and_b(to_date, N, sn, bin_arr_a, len_a):
    sc = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(sc):
        return None
    df = pandas.read_csv(sc)
    if str(df['trade_date'][0]) != str(to_date):
        analysis_stock(sn)
        df = pandas.read_csv(sc)
    n_arr = []
    d_time = 0
    for row in df.index:
        di = DayInfo(sn, df.loc[row])
        if len(n_arr) == len_a - 1:
            break
        x = '1' if di.pct_chg > 0 else '0'
        if row == d_time and di.pct_chg <= 0:
            d_time += 1
        n_arr.append(x)
    arr_b = ['0b1']
    arr_b.extend(n_arr)
    bin_arr_b = ''.join(arr_b)
    a_and_b = bin(eval(bin_arr_a) & eval(bin_arr_b))
    if str(a_and_b).count('1') > N:
        logger.info(f'{bin_arr_a} = bin_arr_a')
        logger.info(f'{bin_arr_b} = bin_arr_b')
        logger.info(f'{a_and_b} = a_and_b')
        res = re.findall('stocks/(.*).csv', sc)
        link_code_arr = res[0].split('.')
        link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
        hyperlink = f'"https://xueqiu.com/S/{link_code}"'
        date_arr_hyp = f'{d_time},{N},=HYPERLINK({hyperlink}),{res[0]}'
        return date_arr_hyp
    return None


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


if __name__ == '__main__':
    # if len(sys.argv) == 2:
    #     D = int(sys.argv[1])
    #     N = 11
    #     arr_len = 50
    # elif len(sys.argv) == 3:
    #     D = int(sys.argv[1])
    #     N = int(sys.argv[2])
    #     arr_len = 50
    # elif len(sys.argv) == 4:
    #     D = int(sys.argv[1])
    #     N = int(sys.argv[2])
    #     arr_len = int(sys.argv[3])
    # else:
    D = True
    N = 20
    arr_len = 50
    bin_arr_a, len_a, to_date = run(D, N)
    df = pd.read_csv('all.csv')
    full_path_csv = f'{to_date}_get_ts.csv'
    n_arr = []
    ts_code_arr = []
    with open(full_path_csv, 'w', encoding='utf-8') as aa:
        aa.write(f'DOWN_TIME,N,LINK,CODE,NAME,INDUS')
        while len(n_arr) < arr_len:
            n_arr = []
            N -= 1
            logger.info(f'cal N={N}')
            for row in df.index:
                sn = StockNumber(df.loc[row])
                msg = get_a_and_b(to_date, N, sn, bin_arr_a, len_a)
                if msg is not None:
                    n_arr.append(msg)
                    if sn.name in ts_code_arr:
                        continue
                    ts_code_arr.append(sn.name)
                    w_msg = f'\n{msg},{sn.name},{sn.industry}'
                    logger.success(w_msg)
                    aa.write(w_msg)
    sort_csv(full_path_csv, ['DOWN_TIME', 'N'], [False, False])
